﻿#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
#include <gdiplus.h>
#include<vector>
#pragma comment(lib, "gdiplus.lib")

using namespace std;
using namespace Gdiplus;
struct Vertex
{
	double x;
	double y;
};
int main() {
	GdiplusStartupInput gdiplusstartupinput;
	ULONG_PTR gdiplustoken;
	GdiplusStartup(&gdiplustoken, &gdiplusstartupinput, NULL);

	wstring infilename(L"1.png");
	string outfilename("color.dat");

	Bitmap* bmp = new Bitmap(infilename.c_str());
	UINT height = bmp->GetHeight();
	UINT width = bmp->GetWidth();
	cout << "width " << width << ", height " << height << endl;

	Color color;
	ofstream fout(outfilename.c_str());
	int R, G, B;
	vector<Vertex>vertexVec;
	Vertex boxMin, boxMax,boxCent;
	boxMin.x = boxMin.y = DBL_MAX;
	boxMax.x = boxMax.y = -DBL_MAX;
	for (int y = 0; y < height; y++)
	{
		for (int x = 0; x < width; x++)
		{
			bmp->GetPixel(x, y, &color);
			R = (int)color.GetRed();
			G = (int)color.GetGreen();
			B = (int)color.GetBlue();
			if (R != 255 && G != 255 && B != 255)
			{
				boxMin.x = min(x, boxMin.x);
				boxMin.y = min(-y, boxMin.y);
				boxMax.x = max(x, boxMax.x);
				boxMax.y = max(-y, boxMax.y);
				vertexVec.emplace_back(Vertex{ (double)x,(double)-y });
			}
		}
	}
	boxCent.x = (boxMax.x + boxMin.x) / 2;
	boxCent.y = (boxMax.y + boxMin.y) / 2;
	Vertex boxMinInput, boxMaxInput,boxCentInput;
	boxMinInput.x = boxMinInput.y = 0.2;
	boxMaxInput.x = boxMaxInput.y = 0.8;
	boxCentInput.x = (boxMaxInput.x + boxMinInput.x) / 2;
	boxCentInput.y = (boxMaxInput.y + boxMinInput.y) / 2;

	double centMoveX = boxCentInput.x- boxCent.x;
	double centMoveY = boxCentInput.y - boxCent.y;

	double scale = sqrt(pow(boxMaxInput.x - boxCentInput.x, 2) + pow(boxMaxInput.y - boxCentInput.y, 2))/sqrt(pow(boxMax.x - boxCent.x, 2) + pow(boxMax.y - boxCent.y, 2));

	for (size_t iVertex = 0; iVertex < vertexVec.size(); ++iVertex)
	{
		vertexVec[iVertex].x = scale * (vertexVec[iVertex].x - boxCent.x)+ boxCent.x;
		vertexVec[iVertex].y = scale * (vertexVec[iVertex].y - boxCent.y)+ boxCent.y;
		vertexVec[iVertex].x += centMoveX;
		vertexVec[iVertex].y += centMoveY;
		fout << vertexVec[iVertex].x << " " << vertexVec[iVertex].y << endl;
	}


	fout.close();

	delete bmp;
	GdiplusShutdown(gdiplustoken);
	return 0;
}